### 根据json 字典中的ROI 对图像进行裁剪 并保存
import json
import numpy as np
import cv2
import os
from shutil import copyfile
def json_dict(json_name):
    f = open(json_name,encoding="utf-8")
    user_dic = json.load(f)
    print(user_dic.keys())
    return user_dic
    # 【1. 获取文件绝对路径】
def _getFilesPath(file_dir):
    filenames = []
    img_name = []
    for root, dirs, files in os.walk(file_dir,topdown=False):
        for name in files:
            # 只选择bmp jpg 
            # print(name.split('.')[-1])
            if name.split('.')[-1] in ['bmp','jpg','jpeg','png']:
                # print(os.path.join(root, name))
                filenames.append(os.path.join(root, name))
                img_name.append(name)
    return filenames,img_name
def _cut_img_site_points(set_roi = [1,1,100,100],cut_num = 10,min_side = 50):
    roi_w = set_roi[2] - set_roi[0]
    roi_h = set_roi[3] - set_roi[1]
    # cut_img_side = roi_w *2/3 if roi_w *2/3> min_side else roi_w
    cut_img_side = roi_w

    # 在指定区域内 随机裁剪n 个正方形图片并保存
    # set_roi = [1,1,100,100]  左上角坐标和右下角坐标 
    # cut_num 裁剪图片数量 5个   cut_img_side 裁剪边长 像素数
    # cropped = img[0:128, 0:512]  # 裁剪坐标为[y0:y1, x0:x1]
    _seed_points = np.random.rand(2,cut_num)
    x_points = list(_seed_points)[0]
    y_points = list(_seed_points)[1]
    # print(x_points,y_points)
    # 计算 裁剪图像中心坐标
    center_x = [int((roi_w -cut_img_side) * x + 0.5*cut_img_side + set_roi[0]) for x in x_points]
    center_y = [int((roi_h -cut_img_side) * y + 0.5*cut_img_side + set_roi[1]) for y in y_points]
    # print(center_x,center_y)
    cut_img_lt_rd = [[int(x-0.5*cut_img_side),
                    int(y - 0.5*cut_img_side),
                    int(x+0.5*cut_img_side),
                    int(y + 0.5*cut_img_side)] for x,y in zip(center_x,center_y)]
    # print(cut_img_lt_rd)
    return cut_img_lt_rd

def cut_img(img_name,cut_points,save_path = './'):
    origin_img = cv2.imread(img_name)
    # cv2.imshow("img",origin_img)
    (filepath,tempfilename) = os.path.split(img_name)
    # print("img_name = {}".format(img_name))
    try:
        for i,points in enumerate(cut_points):
            if len(tempfilename.split('_')) > 2:
                tmp_name = tempfilename.split('_')[-3] + tempfilename.split('_')[-2] + '_'+ str(i) +'.'+ tempfilename.split('.')[-1]
                # print("tmp_path = {}".format(tmp_name))
            else:
                tmp_name = tempfilename.split('_')[0] + tempfilename.split('_')[1].split('.')[0] + '_'+ str(i) +'.'+ tempfilename.split('.')[-1]
                # print("tmp_path = {}".format(tmp_name))
            tmp_img = origin_img[points[1]:points[3], points[0]:points[2]]
            tmp_path = os.path.join(save_path,tmp_name)
            
            
            cv2.imwrite(tmp_path,tmp_img)
            # break
    except:
        print("error =")


if __name__=='__main__':
    img_info = json_dict('./spray_roi.json')
    cut_img_num = 10  # 设定每个ROI裁剪的图片数量
    cut_img_minSide = 200 # 裁剪图片的最小尺寸，如果小于该尺寸 则按ROI的长度裁剪

    # 循环每个场景进行裁剪
    for item in img_info.keys():
        # 从指定文件夹内获取原始图片 并裁剪保存
        imgs_path,imgs_name = _getFilesPath(img_info[item]['file_path'])
        img_name = []
        for i,img in enumerate(imgs_path):
            # 图片清洗 按小时筛选
            try:
                # if len(imgs_name[i]) > 18:
                #     img_time_hour = imgs_name[i].split("_")[-3] + "_" + imgs_name[i].split("_")[-2][0:3]
                # else:
                #     img_time_hour = imgs_name[i].split("_")[0] + imgs_name[i].split("_")[1][0:3]
                # if img_time_hour in img_name:
                #     continue
                # else:
                    # img_name.append(img_time_hour)
                    # save_path ="F:\\2020TIE\\20200903_spray\\clean_img\\" + img_info[item]['file_path'].split("\\")[-1]            
                    # if not os.path.exists(save_path):
                    #     os.makedirs(save_path)
                    # if len(imgs_name[i]) > 18:
                    #     copyfile(img, save_path + "\\" + imgs_name[i].split("_")[-3] + "_" + imgs_name[i].split("_")[-2]+".jpg")
                    # else:
                    #     copyfile(img, save_path + "\\" + imgs_name[i])
                    # print(imgs_name[i].split("_")[1] + "_" + imgs_name[i].split("_")[2]+".jpg")
                    # print(save_path + "\\" + imgs_name[i].split("_")[1:-1])
                    # 根据参数 随机获取裁剪图片的左上右下坐标
                if len(img_info[item]['ROI']) < 4:
                    break
                points = _cut_img_site_points(img_info[item]['ROI'],cut_img_num,cut_img_minSide)
                cut_img(img,points,img_info[item]['save_path'])

                # cv2.imshow("img",origin_img)      
            except:
                print("img = {}".format(img))
        # print(img_name)
        # break
    pass